/**
 * 
 */
package denaris.core;

import javax.microedition.lcdui.Graphics;

import denaris.midlet.GameScreen;
import denaris.midlet.DenarisGameCanvas.DisplayProperties;

/**
 * @author stkl23
 * 
 */
public class Starfield {
	private int[] stars;

	private int[] colors;
	
	/** an offset value that is added to the y-coordinate of every star - used for vertical scrolling */
	private int verticalOffset = 0;

	public Starfield(int starCount) {
		this(starCount, new int[] { 0xC0C0C0, 0xA0A0A0, 0x808080, 0x606060,
				0x404040, 0x202020 });
	}

	public Starfield(int starCount, int[] colors) {
		this.colors = colors;
		// initialize the star array
		stars = new int[starCount];
		reset();
	}
	
	public void reset() {
		for (int i = 0; i < stars.length; i++) {
			int color = (GameScreen.RANDOM.nextInt() & 0x0F) % colors.length;
			int x = GameScreen.nextPositiveInt(DisplayProperties.DISPLAY_WIDTH);
			int y = GameScreen.nextPositiveInt(GameScreen.getInstance().getMap().getHeight()) + DisplayProperties.GAME_TOP;
			// decode these values into one int
			stars[i] = x | (y << 12) | (color << 24) | (color << 28);
		}
	}

	public void update() {
		for (int i = 0; i < stars.length; i++) {
			if (((stars[i] >> 28) & 0x0F) == 0) {
				// reset the delay value
				stars[i] |= ((stars[i] >> 24 & 0x0F) << 28);
				// check the x coordinate
				if ((stars[i] & 0xFFF) == 0) {
					// reset the x coordinate
					stars[i] |= DisplayProperties.DISPLAY_WIDTH;
				} else {
					// move it left
					stars[i]--;
				}
			} else {
				// wait
				stars[i] -= (0x1 << 28);
			}
		}
	}
	
	public void moveVertical(int dy) {
		verticalOffset += dy;
	}

	public void paint(Graphics g) {
		for (int i = 0; i < stars.length; i++) {
			int x = stars[i] & 0xFFF;
			int y = (stars[i] >> 12) & 0xFFF;
			int color = colors[(stars[i] >> 24) & 0xF];
			g.setColor(color);
			g.fillRect(x, y + verticalOffset, 1, 1);
		}
	}
}
